<template>
  <div>
    <div class="container mx-auto p-4">
      <div class="bg-primary text-white font-bold text-xl p-4 rounded-t-lg text-center">管理员信息列表</div>
      <div style="padding: 10px;height: 35px;">

        <div style="float: left;">
          <label class="mr-2 font-semibold">用户名：</label>
          <el-input v-model="username" style="width: 120px" placeholder="请输入用户名" />
          <label class="mr-2 font-semibold">权限：</label>
          <el-select v-model="promiss" style="width: 120px">
            <el-option label="超级管理员" value="超级管理员" />
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </div>
        <div style="float: right;">
          <el-button plain @click="fetchData">
            <i class="fa fa-search mr-1"></i>查询
          </el-button>
          <el-button plain @click="handleAdd">
            <i class="fa fa-plus mr-1"></i>新增
          </el-button>
        </div>

      </div>

      <div>
        <el-table :data="tableData" style="width: 1000px" v-loading="loading" stripe>
        <el-table-column fixed prop="username" label="用户名" width="250" />
        <el-table-column prop="password" label="密码" width="250" />
        <el-table-column prop="promiss" label="权限" width="250" :formatter="formatPromiss" />
        <el-table-column fixed="right" label="操作" width="250">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
              <i class="fa fa-trash mr-1"></i>删除
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
              <i class="fa fa-edit mr-1"></i>编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>

      <div class="mt-4">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
          :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination-container" />
      </div>
    </div>
  </div>

  <!-- 编辑对话框 -->
  <el-dialog v-model="editDialogVisible" :title="isEdit ? '编辑管理员' : '新增管理员'">
    <el-form :model="currentEditRow" label-width="100px">
      <el-form-item label="用户名" :rules="{ required: true, message: '请输入用户名', trigger: 'blur' }">
        <el-input v-model="currentEditRow.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :rules="{ required: true, message: '请输入密码', trigger: 'blur' }">
        <el-input v-model="currentEditRow.password" type="password" autocomplete="off" show-password />
      </el-form-item>
      <el-form-item label="权限" :rules="{ required: true, message: '请选择权限', trigger: 'change' }">
        <el-select v-model="currentEditRow.promiss">
          <el-option label="超级管理员" value="超级管理员" />
          <el-option label="管理员" value="管理员" />
          <el-option label="普通用户" value="普通用户" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">确认</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const tableData = ref([]);
const username = ref('');
const promiss = ref('');
// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const isEdit = ref(false); // 是否为编辑状态
// 加载状态
const loading = ref(false);
// 编辑相关
const editDialogVisible = ref(false);
const currentEditRow = ref({});

// 获取token
const getToken = () => localStorage.getItem('token') || '';

// 权限格式化方法
const formatPromiss = (row, column, cellValue) => {
  return cellValue || '--';
};

// 获取数据
function fetchData() {
  axios.get('http://127.0.0.1:8000/user/search/', {
    params: {
      username: username.value,
      promiss: promiss.value,
      page: currentPage.value,
      pagesize: pageSize.value,
    },
    headers: {
      'token': getToken(),
    },
  })
  .then((response) => {
    if (response.data.code === '1001') {
      tableData.value = response.data.data;
      total.value = response.data.total;
      ElMessage.success(response.data.message || '查询成功');
    } else {
      ElMessage.error(response.data.message || '查询失败');
    }
  })
  .catch((error) => {
    console.error('Fetch data error:', error);
    ElMessage.error('数据加载失败');
  })
  .finally(() => {
    loading.value = false;
  });
}

// 编辑处理
function handleEdit(row) {
  currentEditRow.value = { ...row };
  editDialogVisible.value = true;
  isEdit.value = true;
}

// 新增处理
function handleAdd() {
  currentEditRow.value = {
    username: '',
    password: '',
    promiss: '管理员',
  };
  editDialogVisible.value = true;
  isEdit.value = false;
}

// 提交编辑/新增
function submitEdit() {
  const requestData = { ...currentEditRow.value };

  axios.post('http://127.0.0.1:8000/user/add/', requestData, {
    headers: {
      'token': getToken(),
    },
  })
  .then((response) => {
    if (response.data.code === '1001') {
      ElMessage.success(isEdit.value? '修改成功' : '添加成功');
      editDialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(response.data.message || (isEdit.value? '修改失败' : '添加失败'));
    }
  })
  .catch((error) => {
    console.error('Submit error:', error);
    ElMessage.error('请求失败，请重试');
  });
}

// 删除处理
function handleDelete(row) {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.username} 吗？`,
    '提示',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  )
  .then(() => {
    return axios.delete(`http://127.0.0.1:8000/user/delete/${row.id}`, {
      headers: {
        'token': getToken(),
      },
    });
  })
  .then((response) => {
    if (response.data.code === '1001') {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  })
  .catch((error) => {
    if (error.response?.data?.code === '-1003') {
      ElMessage.error('请先登录');
    }
    console.error('Delete error:', error);
  });
}

// 分页处理
function handleSizeChange(newSize) {
  pageSize.value = newSize;
  fetchData();
}

function handleCurrentChange(newPage) {
  currentPage.value = newPage;
  fetchData();
}

// 初始化加载
onMounted(() => {
  fetchData();
});
</script>
<style scoped>
/* 主容器优化 */
.container {
  max-width: 1200px;
  padding: 2rem 1rem;
}

/* 标题栏样式优化 */
.bg-primary {
  background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
  box-shadow: 0 2px 8px rgba(216, 116, 116, 0.1);
  border: 1px solid #8e8a8a;
  padding: 12px 15px;

  border-radius: 8px 8px 0 0;
  color: white;
  font-weight: bold; 
  font-size: 1.5em;
}

/* 内容卡片样式 */
.bg-white {
  border-radius: 0 0 8px 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.3s ease;
}

.bg-white:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}


/* 输入框和选择器样式优化 */
.el-input,
.el-select {
  --el-input-border-radius: 6px;
  --el-input-hover-border-color: #409EFF;
}

/* 按钮样式优化 */
.el-button {
  border-radius: 6px;
  padding: 0.65rem 1.5rem;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.el-button--primary:hover {
  background: #337ecc;
}

/* 表格样式优化 */
.el-table {
  --el-table-border-color: #030303;
  --el-table-header-bg-color: #f8fafc;
  --el-table-row-hover-bg-color: #f5f8ff;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  font-weight: 700;
  color: #475569;
}



/* 操作按钮样式 */
.el-button--link {
  padding: 0.5rem;
  margin: 0 0.5rem;
}

.el-button--link i {
  margin-right: 0.3rem;
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.el-dialog__header {
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  margin: 0;
  padding: 1.5rem;
}

.el-dialog__body {
  padding: 2rem;
}

.el-form-item {
  margin-bottom: 1.5rem;
}

/* 分页组件优化 */
.pagination-container {
  margin-top: 2rem;
  padding: 1rem;
  background: #f8fafc;
  border-radius: 8px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .flex-wrap>div {
    width: 100%;
  }

  .el-input,
  .el-select {
    width: 100% !important;
  }

  .ml-auto {
    margin-left: 0;
    width: 100%;
    justify-content: flex-end;
  }
}
</style>